import React, { useEffect, useState } from 'react';
import { getStuListAPI, delStuItemAPI } from '@/server/category';
import { Space, Table, Button } from 'antd';
import DialogBox from './components/dialog-box';

export default function list() {
  // 表头内容
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '分数',
      dataIndex: 'score',
      key: 'score',
      align: 'center',
    },
    {
      title: '生日',
      dataIndex: 'created_at',
      key: 'created_at',
      align: 'center',
    },
    {
      title: '地区',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <span>{record.province}</span>
          <span>{record.city}</span>
        </Space>
      ),
    },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            onClick={() => compileStuItem(record)}
          >
            编辑
          </Button>
          <Button
            type="primary"
            size="small"
            danger
            onClick={() => del(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];
  // 定义渲染数据
  const [list, setList] = useState([]);
  // 设置加载状态
  const [isLoading, setIsLoading] = useState(false);
  // 请求数据函数
  const getStuListFn = async () => {
    // 开启加载状态
    setIsLoading(true);
    const res = await getStuListAPI();
    console.log(res);
    // 设置渲染数组
    setList(res.results);
    // 关闭加载状态
    setIsLoading(false);
  };
  // 请求数据
  useEffect(async () => {
    getStuListFn();
  }, []);
  // 删除数据
  const del = (data) => {
    delStuItemAPI(data.id);
    // 重新请求数据
    getStuListFn();
  };
  // 编辑数据
  const [isShow, setShow] = useState(false);
  const [globalItem, setGlobalItem] = useState(null);
  const compileStuItem = (item) => {
    // 获取当前点击项数据
    setGlobalItem(item);
    // 显示弹框
    setShow(true);
  };
  return (
    <>
      <Table
        columns={columns}
        dataSource={list}
        rowKey="objectId"
        loading={isLoading}
      />
      <DialogBox isShow={isShow} item={globalItem} setShow={setShow} />
    </>
  );
}
